#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>

using namespace std;

// 2561. 重排水果
// https://leetcode.cn/problems/rearranging-fruits/description/?envType=daily-question&envId=2025-08-02

class Solution {
public:
    long long minCost(vector<int>& basket1, vector<int>& basket2) {
        // 去交集
        unordered_map<int, int> basketCnt;
        for (int i = 0; i < basket1.size(); i++){
            basketCnt[basket1[i]]++;
            basketCnt[basket2[i]]--;
        }

        int minCost = INT32_MAX;
        vector<int> a, b;
        for (auto &[cost, freq] : basketCnt)
        {
            if(freq % 2 != 0){
                return -1;
            }
            minCost = min(minCost, cost);

            if(freq > 0){
                for (int i = 0; i < freq / 2; i++){
                    a.push_back(cost);
                }
            }else{
                for (int i = 0; i < -freq / 2; i++){
                    b.push_back(cost);
                }
            }
        }
        sort(a.begin(), a.end());
        sort(b.begin(), b.end(), greater<int>());

        long long ans = 0;
        for (int i = 0; i < a.size(); i++){
            ans += min(min(a[i], b[i]), minCost * 2);
        }
        return ans;
    }
};

int main()
{
    return 0;
}